import axios from 'axios'
import toastr from 'toastr'
import {getToken} from './token.js'
import router from "../router";

const instance = axios.create({
    baseURL: 'http://localhost:8082',
});

instance.interceptors.request.use(async function (config) {
    if (config.auth) {
        try{
            let accessToken = await getToken() ;
            if (accessToken != null) {
                // 添加一个请求头信息
                config = {
                    ...config,
                    headers: {
                        ...config.headers,
                        "Authorization": "Bearer " + accessToken
                    }
                };
            }
            delete config.auth ;
        }catch (e){
            // 跳转到登录
            router.push({name: "login"})
            return Promise.reject("No access token available");
        }
    }
    return config ;
});


instance.interceptors.response.use(function(response) {
    // 获取响应的业务状态
    let ret = response.data ;
    // 如果 status 不为 true
    if (!ret.status && (ret.code === 20000 || ret.code === 50000 || ret.code === 60000 || ret.code === 70000 || ret.code === 99999 )) {
        toastr.warning(ret.message, '警告');
        return Promise.reject(ret) ;
    }else if (!ret.status && ret.code === 40000) {
        router.push({name: "login"})
    }
    return ret ;
}, function(error){
    if (error.response && (error.response.status === 401)) {
        toastr.warning(error.response.data.message);
    }else{
        toastr.warning("未知错误、错误码：" + error.code);
    }
    throw error ;
});

export default instance ;

